﻿using Airon.Dapper.Internal;
using Airon.DatabaseAccessor;

using Dapper;

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using static Airon.DatabaseAccessor.DapperRepository;

namespace Airon.Extras.DatabaseAccessor.Dapper.Internal
{
    public static class DapperDbContext
    {
        /// <summary>
        /// 获取数据库连接字符串 
        /// </summary>
        /// <param name="dblist"></param>
        /// <param name="dbtype"></param>
        /// <returns></returns>
        public static IDbConnection GetContext(this List<IDbConnectionConfig> dblist, SqlDataBaseConfig.DbType dbtype = SqlDataBaseConfig.DbType.Master,string sqlProvider=SqlProvider.SqlServer)
        {
            IDbConnection result =null;
            var data = dblist.Where(s => s._dbType == dbtype);
            IDbConnectionConfig dt = null;
            if (data.Any() && dblist.Count > 1)
            {
                switch (dbtype)
                {
                    case SqlDataBaseConfig.DbType.Master:
                        dt = data.First();
                        result = Activator.CreateInstance(SqlProvider.GetDbConnectionType(sqlProvider), new[] { dt._db }) as IDbConnection;
                        break;
                    case SqlDataBaseConfig.DbType.Slave:
                        dt=data.ToList()[new Random().Next(0, data.Count())];
                        result = Activator.CreateInstance(SqlProvider.GetDbConnectionType(sqlProvider), new[] { dt._db }) as IDbConnection;
                        break;
                    default:
                        return null;
                }
            }
            else
            {
                if (dblist.Count > 0)
                {
                    result = Activator.CreateInstance(SqlProvider.GetDbConnectionType(sqlProvider), new[] { dblist.First()._db }) as IDbConnection;
                }
                else
                {
                    return null;
                }
            }
            if (result.State!=ConnectionState.Open) result.Open();
            return result;
        }
    }
}
